//
//  PresentionAnimator.m
//  自定义转场动画
//
//  Created by zxy on 2019/4/19.
//  Copyright © 2019 zxy. All rights reserved.
//

#import "PresentionAnimator.h"
#import "PresentationController.h"
static double transDuration = 0.25;
@interface PresentionAnimator()
///是否是Present
@property(nonatomic,assign)BOOL isPresent;
@end
@implementation PresentionAnimator

#pragma mark -UIViewControllerAnimatedTransitioning
///设置动画的时长
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    return transDuration;
}

///展示关闭
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    ///在这里可以实现自己想要的展开和关闭动画
    if(self.isPresent){//展开
        //获取要被展示的view
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        //从0开始展示全部
        toView.transform = CGAffineTransformMakeScale(0.0, 0.0);
        [transitionContext.containerView addSubview:toView];
        //执行动画
        [UIView animateWithDuration:transDuration animations:^{
            //重置
            toView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:YES];
        }];
        
    }else{//关闭
        //获取
        //获取要被展示的view
        UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        fromView.layer.anchorPoint = CGPointMake(0.5, 0.5);
         [transitionContext.containerView addSubview:fromView];
        //执行动画
        [UIView animateWithDuration:transDuration animations:^{
            //0.0:因为CGFolat是不准确的，导致设置为0.0达不到效果，这里将其设置为一个很小的
            fromView.transform = CGAffineTransformMakeScale(0.0, 0.0);
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:YES];
        }];
    }
}


///只要实现了这个方法，系统所有的默认动画都会无效，所有设置有自己控制
//展示
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
     ///present：设置YES
    self.isPresent = YES;
    return self;
}
//隐藏
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    ///dismiss：设置NO
    self.isPresent = NO;
    return self;
}


- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(nullable UIViewController *)presenting sourceViewController:(UIViewController *)source{
    PresentationController *pc = [[PresentationController alloc]initWithPresentedViewController:presented presentingViewController:presenting];
    pc.presentFrame = self.presentFrame;
    return pc;
}

@end
